<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车的实现</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
    <h3>购物车的实现</h3>
    <div id="app">
        <li v-for="book in books">
            <td>编号:{{book.id}}</td>
            <td>书名: {{book.title}}</td>
            <td>价格: {{book.price}}</td>
            <td><button v-on:click="book.count -=1">-</button></td>
            <td>数量: {{book.count}}</td>
            <td><button v-on:click="book.count +=1">+</button></td>
            <td>金额: {{itemPrice(book)}}</td>
        </li>

        <p> 总价:{{totolPrice()}}
        </p>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    books: [
                        { id: 1, title: 'java入门', price: 18, count: 0 },
                        { id: 2, title: 'python入门', price: 27, count: 0 },
                        { id: 3, title: 'redis', price: 36, count: 0 },
                    ]
                }
            },
            methods: {
                itemPrice(book) {
                    return book.count * book.price;
                },
                totolPrice() {
                    let total = 0;
                    for (let b of this.books) {
                        total += b.count * b.price;
                    }
                    return total;
                }
            },
        })

    </script>
</body>

</html>